package com.lagou.controller;

import com.lagou.pojo.User;
import com.lagou.service.CodeDubboService;
import com.lagou.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Reference
    CodeDubboService codeService;

    @GetMapping("/register/{email}/{password}/{code}")
    public Integer regiest(@PathVariable String email,@PathVariable String password,@PathVariable String code,HttpServletResponse response){
        if(userService.isRegiested(email)){
            return 3;
        }
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        Integer validate = codeService.validate(email, code);
        //该邮箱的验证码有效
        if(validate==0){
            //完成注册
            boolean result = userService.regiestUser(user);
            //生成token
//            String token = userService.login(email, password);
//            if(token!=null){
//                Cookie cookie = new Cookie("token",token);
//                response.addCookie(cookie);
//            }
        }
        return validate;
    }

    @GetMapping("/isRegiested/{email}")
    public boolean isRegiested(@PathVariable String email){
        boolean rediested = userService.isRegiested(email);
        return rediested;
    }

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable String email, @PathVariable String password, HttpServletResponse response){
        String token = userService.login(email, password);
        if(token!=null){
            Cookie cookie = new Cookie("token",token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return token;
    }

    @GetMapping("/info/{token}")
    public String getInfo(@PathVariable String token,HttpServletRequest request){
        for(Cookie cookie : request.getCookies()){
            if(cookie.getName().equals("token")){
                token = cookie.getValue();
            }
        }
        User user = userService.getInfo(token);
        return user.getEmail();
    }

}
